package entity

import (
	"kop/modules/shop/configuration"
	"kop/modules/shop/configuration/refreshtype"
	"time"
)

type Shop struct {
	RoleID      int32 `gorm:"primary_key"`
	ShopID      int32 `gorm:"primary_key"`
	RefreshNum  int32
	RefreshTime int64
	Version     int32
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

//func (Role) TableName() string {
//	return "roles"
//}

func (s *Shop) CDStart() {

	var now = time.Now()
	var year, month, day = now.Date()
	var today = time.Date(year, month, day, 0, 0, 0, 0, time.Local).Unix()

	var conf, err = configuration.GetShopByShopID(s.ShopID)
	if err != nil {
		panic(err)
	}

	switch conf.Refresh.Type {
	case refreshtype.SixHour:
		for i := int64(1); i <= 5; i++ {
			var future = today + i*6*3600
			if future > time.Now().Unix() {
				s.RefreshTime = future
			}
		}

	case refreshtype.Day:
		s.RefreshTime = today + 86400
	default:
		s.RefreshTime = 0
	}
}

func (s *Shop) GetCD() int32 {

	//var conf, err = configuration.GetShopByShopID(s.ShopID)
	//if err != nil {
	//	panic(err)
	//}

	if sec := s.RefreshTime - time.Now().Unix(); sec > 0 {
		return int32(sec)
	}

	return 0
}

func (s *Shop) VersionChange() bool {

	var conf, err = configuration.GetShopByShopID(s.ShopID)
	if err != nil {
		panic(err)
	}

	return conf.Refresh.Version != s.Version
}
